﻿/*
 * 使用方法：
   using CommonTools;
   public cs_common tools = new cs_common();
   tools.XXX();
 * 对于静态函数也可以：
 * cs_common.XXX();
*/ 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Threading;

//需要在工程里引用相应的内容(添加→引用→.NET)
//using Microsoft.Office.Interop.Excel;
//using Microsoft.Office.Interop.Word;

using System.Data.OleDb;
using System.Data;
using System.Reflection;
using System.Diagnostics;
using Microsoft.Win32;

namespace CommonTools
{
    public class cs_common
    {
        public cs_common()
        {
            Console.Out.WriteLine("通用工具类，包含：网络通信、ACCESS数据库操作、操作Office。");
            Console.Out.WriteLine("消息框Messagebox");
            Console.Out.WriteLine("常用代码：dataGridView显示行号");
        }

        public static bool RunExe(string app,string arg="")
        {
            try
            {
                if(arg.Length>0)
                    System.Diagnostics.Process.Start(app,arg);
                else
                    System.Diagnostics.Process.Start(app);
                return true;
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
                return false;
            }
        }

        //得到当前exe文件所在的路径
        public static string GetAppPath()
        {
            try
            {
                string apppath = System.Windows.Forms.Application.StartupPath;
                if (!apppath.EndsWith("\\"))
                    apppath += "\\";
                return apppath;
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
                return "";
            }
        }

        //得到当前Service文件所在的路径
        public static string GetServicePath()
        {
            try
            {
            //CommandLine without the first and last two characters
            //Path.GetDirectory seems to have some difficulties with these (special chars maybe?)
            string cmdLine = Environment.CommandLine.Remove(Environment.CommandLine.Length - 2, 2).Remove(0, 1);
            string workDir = Path.GetDirectoryName(cmdLine);


                if (!workDir.EndsWith("\\"))
                    workDir += "\\";
                return workDir;
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
                return "";
            }
        }

        /// <summary>
        /// 判断当前程序是否正在运行
        /// （用于实现程序只能启动一个实例）
        /// </summary>
        public static bool IsInstanceRunning()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);

            foreach (Process process in processes)
            {
                if (process.Id != current.Id)
                {

                    if (process.MainModule.FileName == current.MainModule.FileName)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        public static string GetDateTimeStr()
        {
            return DateTime.Now.ToString("yyyyMMddHHmmss");
        }

        //取今天的毫秒数做流水号
        public static string GetSerialNo()
        {
            //return DateTime.Now.Ticks.ToString();
            //DateTime centuryBegin = new DateTime(2000, 1, 1);
            DateTime currentDate = DateTime.Now;
            DateTime centuryBegin = new DateTime(currentDate.Year, currentDate.Month, currentDate.Day);
            long elapsedTicks = currentDate.Ticks - centuryBegin.Ticks;

            TimeSpan elapsedSpan = new TimeSpan(elapsedTicks);
            long span = (long)elapsedSpan.TotalMilliseconds;
            return span.ToString();
        }

        /// <summary>
        /// 从全路径文件名中分离出路径（不含结尾斜杠）
        /// </summary>
        /// <param name="fullpathname"></param>
        /// <returns>路径</returns>
        public static string GetPathFromFullName(string fullpathname)
        {
            string strPath = fullpathname.Substring(0, fullpathname.LastIndexOf("\\"));
            //string strName = fullpathname.Substring(fullpathname.LastIndexOf("\\") + 1);
            return strPath;
        }

        /// <summary>
        /// 从全路径文件名中分离出文件名
        /// </summary>
        /// <param name="fullpathname"></param>
        /// <returns>文件名</returns>
        public static string GetFilenameFromFullName(string fullpathname)
        {
            //string strPath = fullpathname.Substring(0, fullpathname.LastIndexOf("\\"));
            string strName = fullpathname.Substring(fullpathname.LastIndexOf("\\") + 1);
            return strName;
        }


        #region 读写INI文件

        [DllImport("kernel32")]//返回0表示失败，非0为成功
        private static extern long WritePrivateProfileString(string section,string key,
            string val,string filePath);

        [DllImport("kernel32")]//返回取得字符串缓冲区的长度
        private static extern long GetPrivateProfileString(string section,string key,
            string def,StringBuilder retVal,int size,string filePath);


        public static string ReadIniData(string Section,string Key,string NoText,string iniFilePath)
        {
            if(File.Exists(iniFilePath))
            {
                StringBuilder temp = new StringBuilder(1024);
                GetPrivateProfileString(Section,Key,NoText,temp,1024,iniFilePath);
                return temp.ToString();
            }
            else
            {
                return String.Empty;
            }
        }

        public static bool WriteIniData(string Section,string Key,string Value,string iniFilePath)
        {
            if(File.Exists(iniFilePath))
            {
                long OpStation = WritePrivateProfileString(Section,Key,Value,iniFilePath);    
                if(OpStation == 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            else
            {
                return false;
            }
        }

        #endregion

        #region 字符串与数字相互转换
        public static double String2Double(string s)
        {
            double d = 0;
            if (s.Length == 0 || s == "inf")
                return d;
            try
            {
                d = double.Parse(s);
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
            }
            return d;
        }

        public static float String2Float(string s)
        {
            float d = 0;
            if (s.Length == 0 || s == "inf")
                return d;
            try
            {
                d = float.Parse(s);
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
            }
            return d;
        }

        public static int String2Int(string s)
        {
            int d = 0;
            if (s.Length == 0 || s == "inf")
                return d;
            try
            {
                d = int.Parse(s);
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
            }
            return d;
        }

        #endregion
        /*
        #region 操作Office的相关函数
        //加载Excel到DataSet
        //  DataSet ds = tools.LoadDataFromExcel("c:\\a.xls");
        //  DataRow row = ds.Tables[0].Rows[0];
        //  Console.Out.WriteLine(row[0].ToString());
        //
        public static DataSet LoadDataFromExcel(string filePath)
        {
            try
            {
                string strConn;
                strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
                OleDbConnection OleConn = new OleDbConnection(strConn);
                OleConn.Open();
                String sql = "SELECT * FROM  [Sheet1$]";//可是更改Sheet名称，比如sheet2，等等 

                OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);
                DataSet OleDsExcle = new DataSet();
                OleDaExcel.Fill(OleDsExcle, "Sheet1");
                OleConn.Close();
                return OleDsExcle;
            }
            catch (Exception err)
            {
                MessageBox.Show("数据绑定Excel失败!失败原因：" + err.Message, "提示信息",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                return null;
            }
        }
        
        /// <summary>
        /// 设置 Excel 单元格的值
        /// </summary>
        /// <param name="sheet">Excel表格</param>
        /// <param name="strName">单元格的名字，可以是原始名称A1等，
        /// 也可以在excel中为每个单元格起个别名，如：成绩</param>
        /// <param name="strValue">单元格的内容</param>
        /// 需要在工程中添加Microsoft Excel Object Library引用
        public static void SetExcelValue(ref Worksheet sheet, string strName, string strValue)
        {
            try
            {
                Microsoft.Office.Interop.Excel.Range find = null;
                find = sheet.get_Range(strName, Missing.Value);
                if (find != null)
                {
                    find.Value = strValue;
                }
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
            }
        }

        // 输出excel的示例程序
        // 这个文件要根据具体应用重写
        //
        public static void ExportExcel()
        {
            //检测Excel是否安装
            Microsoft.Office.Interop.Excel.Application excelTest = null;
            try
            {
                excelTest = new Microsoft.Office.Interop.Excel.Application();
            }
            catch (Exception)
            {
                MessageBox.Show("无法检测到Excel程序。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excelTest);

            // 寻找模板文件
            string fileName = System.Windows.Forms.Application.StartupPath + "\\模板.xls";
            if (!File.Exists(fileName))
            {
                MessageBox.Show("找不到 Excel 模板文件！", "导出失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            SaveFileDialog saveDlg = new SaveFileDialog();
            saveDlg.Filter = "Excel 文件(*.xls)|*.xls";
            saveDlg.Title = "选择Excel文件导出的路径";
            saveDlg.InitialDirectory = cs_common.getMyDocumentDir();
            DialogResult r = saveDlg.ShowDialog();
            if (r == DialogResult.Cancel)
                return;

            if (File.Exists(saveDlg.FileName))
            {
                File.SetAttributes(saveDlg.FileName, FileAttributes.Normal);
                File.Delete(saveDlg.FileName);
            }

            File.Copy(fileName, saveDlg.FileName, true);
            File.SetAttributes(saveDlg.FileName, FileAttributes.Normal);

            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            if (excel == null)
            {
                MessageBox.Show("无法检测到Excel程序。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            excel.Visible = true;
            System.Reflection.Missing miss = System.Reflection.Missing.Value;

            // 打开新文件
            Workbook workbook = excel.Workbooks.Open(saveDlg.FileName, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss);
            //或新建excel文件
            //excel.Workbooks.Add(miss);

            Worksheet sheet = (Worksheet)excel.ActiveWorkbook.ActiveSheet;

            // 开始填充报表
            SetExcelValue(ref sheet, "打印时间", DateTime.Now.ToLongDateString());
            SetExcelValue(ref sheet, "B2", "小红帽");

            workbook.Save();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
            excel = null;
            GC.Collect();
        }

        public static void SetWordValue(ref Microsoft.Office.Interop.Word._Document MyDoc, string name, string value)
        {
            Object BookMarkXH = name;    //word文档里一个名为XH的书签
            if (MyDoc.Bookmarks.Exists(name))
            {
                MyDoc.Bookmarks.get_Item(ref BookMarkXH).Select();
                MyDoc.Bookmarks.get_Item(ref BookMarkXH).Range.Text = value;
            }
        }

        //输出word的示例程序
        //
        public static void ExportWord()
        {
            //检测Excel是否安装
            Microsoft.Office.Interop.Word.Application WordTest = null;
            try
            {
                WordTest = new Microsoft.Office.Interop.Word.Application();
            }
            catch (Exception)
            {
                MessageBox.Show("无法检测到Excel程序。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            System.Runtime.InteropServices.Marshal.ReleaseComObject(WordTest);

            Object Nothing = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word._Document MyDoc;
            Microsoft.Office.Interop.Word._Application MyWord;
            MyWord = new Microsoft.Office.Interop.Word.Application();
            MyWord.Visible = true;
            object FileName = "word.doc";//放的Word模板文件的路径
            //使用上面的word模板文件，生成新word文件
            MyDoc = MyWord.Documents.Add(ref FileName, ref Nothing, ref Nothing, ref Nothing);
            MyDoc.Activate();
            MyWord.Selection.TypeParagraph();//这个也没看出来有什么用。。。
            SetWordValue(ref MyDoc, "name", "liuyuhua");

            try
            {
                //MyDoc.Save();
                MyDoc.SaveAs("newfile.doc");
                MyDoc.Close(ref Nothing, ref Nothing, ref Nothing);
                MyWord.Quit(ref Nothing, ref Nothing, ref Nothing);//退出
            }
            catch (Exception error)
            {
                Console.Out.WriteLine(error.Message);
            }

            System.Runtime.InteropServices.Marshal.ReleaseComObject(MyDoc);
            MyDoc = null;
            GC.Collect();

        }

        #endregion


        private static void CreateDesktopLnk()
        {
            string DesktopPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);//得到桌面文件夹
            IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShellClass();

            IWshRuntimeLibrary.IWshShortcut shortcut =
                (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(DesktopPath + "\\Internet Explorer.lnk");
            shortcut.TargetPath = @"C:\Program Files\Internet Explorer\iexplore.exe";
            shortcut.Arguments = "http://www.baidu.com";// 参数
            shortcut.Description = "Internet Explorer";
            shortcut.WorkingDirectory = @"C:\Program Files\Internet Explorer\";//程序所在文件夹，在快捷方式图标点击右键可以看到此属性
            shortcut.IconLocation = @"C:\Program Files\Internet Explorer\iexplore.exe,0";//图标
            shortcut.Hotkey = "CTRL+SHIFT+T";//热键
            shortcut.WindowStyle = 1;
            shortcut.Save();
        }
        */
        public static string getMyDocumentDir()
        {
            return System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        }

        public static void MsgInfo(IWin32Window owner,string msg)
        {
            MessageBox.Show(owner,msg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        public static void MsgError(IWin32Window owner, string msg)
        {
            MessageBox.Show(owner,msg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        public static void MsgWarn(IWin32Window owner, string msg)
        {
            MessageBox.Show(owner,msg, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        #region byte处理函数

        /// <summary>
        /// byte数组转换为结构体
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        /// 调用方法：
        /// heads=(head)BytesToStuct(datas,typeof(head));
        public static object BytesToStuct(byte[] bytes, Type type)
        {
            //得到结构体的大小
            int size = System.Runtime.InteropServices.Marshal.SizeOf(type);
            //byte数组长度小于结构体的大小
            if (size > bytes.Length)
            {
                //返回空
                return null;
            }
            //分配结构体大小的内存空间
            IntPtr structPtr = System.Runtime.InteropServices.Marshal.AllocHGlobal(size);
            //将byte数组拷到分配好的内存空间
            System.Runtime.InteropServices.Marshal.Copy(bytes, 0, structPtr, size);
            //将内存空间转换为目标结构体
            object obj = System.Runtime.InteropServices.Marshal.PtrToStructure(structPtr, type);
            //释放内存空间
            System.Runtime.InteropServices.Marshal.FreeHGlobal(structPtr);
            //返回结构体
            return obj;
        }

        //把Byte数组的内容转换为字符串
        public static string ByteToString(byte[] buf,int start,int len)
        {
            int vaildLen = 0;
            int b = start;// -1;
            /*
            for (int i = 0; i < len; i++)
            {
                if (buf[i] != '\0')
                {
                    b = i;
                    break;
                }
            }
            */

            if (b >= 0)
            {
                for (int i = b; i < len+b; i++)
                {
                    if (buf[i] != '\0')
                        vaildLen++;
                    else
                        break;
                }
            }
            if (vaildLen > 0)
                return System.Text.Encoding.UTF8.GetString(buf, b, vaildLen);
            else
                return "";
        }

        //把Byte数组的内容转换为字符串
        public static string ByteToString(byte[] buf)
        {
            return System.Text.Encoding.Default.GetString(buf);
        }

        //字符串转换定长byte[]
        public static byte[] StringToBytes(string str,int iLen)
        {
            byte[] buf = new byte[iLen];
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(str);
            int l = byteArray.Length;
            if (l > iLen)
                l = iLen;
            for(int i=0;i<l;i++)
                buf[i]=byteArray[i];

            if (byteArray.Length < iLen)
            {
                byte[] empty = new byte[iLen - byteArray.Length];
                empty.CopyTo(buf, byteArray.Length);
            }
             
            return buf;
        }

        //字符串转换byte[]
        public static byte[] StringToBytes(string str)
        {
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(str);

            return byteArray;
        }

        //在字节数组里找一个字节
        public static int Find_In_Bytes(byte bF, byte[] buf, int len)
        {
            for (int i = 0; i < len; i++)
            {
                if (bF == buf[i])
                    return i;
            }
            return -1;
        }

        public static byte[] intToByte(int i)
        {
            byte[] abyte0 = new byte[4];
            abyte0[0] = (byte)(0xff & i);
            abyte0[1] = (byte)((0xff00 & i) >> 8);
            abyte0[2] = (byte)((0xff0000 & i) >> 16);
            abyte0[3] = (byte)((0xff000000 & i) >> 24);
            return abyte0;
        }


        public static void printBytes(byte[] bytes)
        {
            for (int i = 0; i < bytes.Length; i++)
            {
                Console.Out.Write(bytes[i]+ "-");  
            }
        }

        /// <summary>
        /// 计算校验和
        /// </summary>
        /// <param name="bs"></param>
        /// <param name="iLen"></param>
        /// <returns></returns>
        public static byte CheckSum(byte[] bs, int iLen)
        {
            uint k = 0;
            for (int i = 0; i < iLen; i++)
                k += bs[i];

            k = k & 0x000000ff;

            return (byte)k;
        }

        public static byte CheckSum(byte[] bs, int start, int iLen)
        {
            uint k = 0;
            for (int i = start; i < iLen + start; i++)
                k += bs[i];

            k = k & 0x000000ff;

            return (byte)k;
        }
        //异或和
        public static byte CheckXOR(byte[] bs, int start, int iEnd)
        {
            byte k = bs[start];
            for (int i = start+1; i <= iEnd; i++)
                k ^= bs[i];

            return k;
        }
        
        public static string getMD5Hash32(string inputString)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] encryptedBytes = md5.ComputeHash(Encoding.UTF8.GetBytes(inputString));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < encryptedBytes.Length; i++)
            {
                sb.AppendFormat("{0:X2}", encryptedBytes[i]);
            }
            return sb.ToString();
        }

        public static string getMD5Hash16(string inputString)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(inputString)), 4, 8);
            t2 = t2.Replace("-", "");

            return t2;
        }

        /// <summary>
        /// Base64加密，采用utf8编码方式加密
        /// </summary>
        /// <param name="source">待加密的明文</param>
        /// <returns>加密后的字符串</returns>
        public static string EncodeBase64(string source)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(source);
            try
            {
                return Convert.ToBase64String(bytes);
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// Base64解密
        /// </summary>
        /// <param name="result">待解密的密文</param>
        /// <returns>解密后的字符串</returns>
        public static string DecodeBase64(string result)
        {
            byte[] bytes = Convert.FromBase64String(result);
            try
            {
                return Encoding.UTF8.GetString(bytes);
            }
            catch
            {
                return "";
            }
        }
 
        #endregion

        public static void MySleep(int ms)
        {
            int k = ms / 10;
            for (int i = 0; i < 10; i++)
            {
                // 处理当前界面消息
                Application.DoEvents();

                Thread.Sleep(k);

                // 处理当前界面消息
                Application.DoEvents();
            }
        }

        private static string logPath = cs_common.getMyDocumentDir() + "\\VideoClientLog.log";
        private static string oldPath = cs_common.getMyDocumentDir() + "\\VideoClientOld.log";
        private static int LOG_MAX_LENGTH = 5 * 1024 * 1024;
        /// <summary>
        /// 写日志文件log
        /// </summary>
        /// <param name="log"></param>
        public static void WriteLog(string log)
        {
            try
            {
                File.AppendAllText(logPath, "[" + DateTime.Now.ToString() + "]" + log + "\r\n");
                FileInfo fi = new FileInfo(logPath);
                if (fi.Length > LOG_MAX_LENGTH)
                {
                    File.Delete(oldPath);
                    File.Move(logPath, oldPath);
                }
            }
            catch (Exception)
            {
            	Console.Out.WriteLine(log);
            }
        }

        /// <summary>
        /// 生成图像文件的缩略图
        /// 缩略图的路径与源图像相同，只是主文件名后加m
        /// 如：01.jpg → 01m.jpg
        /// </summary>
        /// <param name="strSrcFile">源图像文件的绝对路径</param>
        public void MakeJpegThumb(String strSrcFile)
        {
            String src = strSrcFile;   //源图像文件的绝对路径
            String dest = src.Substring(0,src.Length-4) + "m" + src.Substring(src.Length-4);    //生成的缩略图图像文件的绝对路径

            int thumbWidth = 100;    //要生成的缩略图的宽度
            System.Drawing.Image image = System.Drawing.Image.FromFile(src); //利用Image对象装载源图像

            //接着创建一个System.Drawing.Bitmap对象，并设置你希望的缩略图的宽度和高度。
            int srcWidth = image.Width;
            int srcHeight = image.Height;
            int thumbHeight = srcHeight * thumbWidth / srcWidth;
            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(thumbWidth, thumbHeight);

            //从Bitmap创建一个System.Drawing.Graphics对象，用来绘制高质量的缩小图。
            System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);

            //设置 System.Drawing.Graphics对象的SmoothingMode属性为HighQuality
            gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //下面这个也设成高质量
            gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

            //下面这个设成High
            gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //把原始图像绘制成上面所设置宽高的缩小图
            System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, thumbWidth, thumbHeight);
            gr.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, System.Drawing.GraphicsUnit.Pixel);

            //保存图像，大功告成！
            bmp.Save(dest);

            //最后别忘了释放资源
            bmp.Dispose();
            image.Dispose();
        }
        /// <summary>
        /// 应用程序未处理的异常统一处理函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void Application_UnhandledException(object sender, EventArgs e)
        {
            /* 以下三行代码要加在Main()函数里的最前面
            //处理未捕获的异常  
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            //处理UI线程异常  
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(cs_common.Application_UnhandledException);
            //处理非UI线程异常  
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(cs_common.Application_UnhandledException);
            */
            string str = "";
            string strDateInfo = "出现应用程序未处理的异常：" + DateTime.Now.ToString() + "\r\n";
            Exception error = null;
            if (e.GetType() == typeof(System.Threading.ThreadExceptionEventArgs))
            {
                System.Threading.ThreadExceptionEventArgs ex = (System.Threading.ThreadExceptionEventArgs)e;
                error = ex.Exception as Exception;
            }
            else if (e.GetType() == typeof(System.UnhandledExceptionEventArgs))
            {
                System.UnhandledExceptionEventArgs ex = (System.UnhandledExceptionEventArgs)e;
                error = ex.ExceptionObject as Exception;
            }

            if (error != null)
            {
                str = string.Format(strDateInfo + "异常类型：{0}\r\n异常消息：{1}\r\n异常信息：{2}\r\n",
                     error.GetType().Name, error.Message, error.StackTrace);
            }
            else
            {
                str = string.Format("Application UnhandledError:{0}", e);
            }

            WriteLog(str);    

            MessageBox.Show("程序发生未知错误（VideoClient）！", "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        /// <summary>
        /// 检查指定的 COM 组件是否已注册到系统中
        /// </summary>
        /// <param name="clsid">COM控件的CLSID，不带大括号</param>
        /// <returns>true: 表示已注册；false: 表示未注册</returns>
        public static System.Boolean IsRegistered(String clsid)
        {

            //参数检查
            System.Diagnostics.Debug.Assert(!String.IsNullOrEmpty(clsid), "clsid 不应该为空");

            //设置返回值
            Boolean result = false;

            //检查方法，查找注册表是否存在指定的clsid
            String key = String.Format(@"CLSID\{{{0}}}", clsid);
            RegistryKey regKey = Registry.ClassesRoot.OpenSubKey(key);
            if (regKey != null)
            {
                result = true;
            }

            return result;
        }//end method
    }

    //----------------------cs_common end------------------------------------//
    /// <summary>
    /// 日志核心类
    /// </summary>
    public class Log
    {
        //public static string logPath = Application.StartupPath +"\\AnyChatDemoLog.log";
        private static string logPath = cs_common.getMyDocumentDir() + "\\VideoServerLog.log";
        private static string oldPath = cs_common.getMyDocumentDir() + "\\VideoServerOld.log";
        private static int LOG_MAX_LENGTH = 5 * 1024 * 1024;
        /// <summary>
        /// 生成log
        /// </summary>
        /// <param name="log"></param>
        public static void WriteLog(string log)
        {
            try
            {
                File.AppendAllText(logPath, "[" + DateTime.Now.ToString() + "]" + log + "\r\n");
                FileInfo fi = new FileInfo(logPath);
                if (fi.Length > LOG_MAX_LENGTH)
                {
                    File.Delete(oldPath);
                    File.Move(logPath, oldPath);
                }
            }
            catch (Exception)
            {
            }
        }
    }
}
